package org.l.codemaker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 严秋旺 on 2016/6/22.
 */
public class Maker {
    private Configuration configuration;
    private File templateDirectory;
    private String encoding = "UTF-8";
    private String outpath = "out";

    public Maker() throws IOException {
        String path = new File("").getAbsoluteFile() + "/template";
        templateDirectory = new File(path);
        initFreemarker();
        Logger.show("初始化成功。");
    }

    private void initFreemarker() throws IOException {
        configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setDirectoryForTemplateLoading(templateDirectory);
        configuration.setDefaultEncoding(encoding);
    }

    public void makeFile(MakeParam makeParam) throws IOException, TemplateException {
        Map data = new HashMap();
        data.put("data", makeParam);

        Logger.show("开始生成代码……");
        String objectName = makeParam.getObjectName();
        String className = objectName.substring(0, 1).toUpperCase() + objectName.substring(1);
        String pakageName = objectName.substring(0, 1).toLowerCase() + objectName.substring(1);

        makeFile(data, "/controller.ftl", "/" + pakageName + "/controller/" + className + "Controller.java");
        makeFile(data, "/dao.ftl", "/" + pakageName + "/dao/" + className + "Dao.java");
        makeFile(data, "/object.ftl", "/" + pakageName + "/entity/" + className + ".java");
        makeFile(data, "/service.ftl", "/" + pakageName + "/service/" + className + "Service.java");
        Logger.show("代码生成完成");
    }

    private void makeFile(Map data, String tpl, String path) throws IOException, TemplateException {
        File outFile = new File(outpath + path);
        Writer out = null;

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        try {
            out = new OutputStreamWriter(new FileOutputStream(outFile), encoding);
            Template template = configuration.getTemplate(tpl);
            template.process(data, out);
            out.flush();
            Logger.show("输出文件" + path);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
